import axios from "axios";
import {getToken, removeToken} from "@/utils/storage";
import router from "@/router";

const request = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0',
    timeout: 5000
})

request.interceptors.request.use((config) => {
    const token = getToken()
    if(token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, (error) => {
    return new Promise(error)
})

request.interceptors.response.use((response) => {
    return response.data
}, (error) => {
    console.log(error)
    if(error.response.status === 401) {
        removeToken()
        router.navigate('/login')
        window.location.reload()
    }
    return new Promise(error)
})

export default request